//
//  mapViewController.m
//  lvtu
//
//  Created by Apple on 12-6-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "mapViewController.h"
#import <MapKit/MapKit.h>
#import "VPPMapAnnotationExample.h"
#import "EventEditViewController.h"
#import "EventDetailViewController.h"
#import "TravelDetailViewController.h"
#import "MoreTripDetailViewController.h"

@implementation mapViewController
@synthesize mapView;
@synthesize langitude = _langitude;
@synthesize latitude = _latitude;
@synthesize placeInfo;
@synthesize isEdit;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        selectedCount = -1;
        selectedPlaceArray = nil;
    }
    return self;
}

- (void)dealloc
{
    if (_mh != Nil) {
        [_mh release];
    }
    if (placeInfo != nil) {
        [placeArray removeAllObjects];
        [placeArray release];
    }
    if (selectedPlaceArray != nil) {
        [selectedPlaceArray removeAllObjects];
        [selectedPlaceArray release];
    }
    [super dealloc];
}

- (void) tonsOfPins {
    srand((unsigned)time(0));
    
//    NSMutableArray *tempPlaces=[[NSMutableArray alloc] init];
    //for (int i = 0; i < 100; i++) {
    
//    VPPMapAnnotationExample *place= [[VPPMapAnnotationExample alloc] init];
//    place.coordinate = CLLocationCoordinate2DMake([_langitude floatValue],[_latitude floatValue]);//([self RandomFloatStart:41.0 end:44.0],[self RandomFloatStart:-9.0 end:-5.0]);
//    
//    place.pinAnnotationColor = MKPinAnnotationColorPurple;
//    place.opensWhenShown = YES;
//    place.title = @"haidilao";
////    place.image = [UIImage imageNamed:@"btn_back_normal.png"];
//    //        [place setTitle:[NSString stringWithFormat:@"Place %d title",i]];
//    [tempPlaces addObject:place];
//    [place release];
//    //}
//    
//    _mh.shouldClusterPins = YES;
//    [_mh setMapAnnotations:tempPlaces];
//    [tempPlaces release];
    if (isEdit == NO) {
        return;
    }
    NSString* templang = [NSString stringWithFormat:@"%f",[_langitude floatValue]*100000];
    NSString* lang = [templang substringToIndex:[templang rangeOfString:@"."].location];
    
    NSString* templati = [NSString stringWithFormat:@"%f",[_latitude floatValue]*100000];
    NSString* lati = [templati substringToIndex:[templati rangeOfString:@"."].location];

    NSDate *today = [NSDate date];
    NSTimeInterval time = [today timeIntervalSince1970];
    NSString* temptime = [NSString stringWithFormat:@"%f",time];
    NSString* s_time = [temptime substringToIndex:[temptime rangeOfString:@"."].location];
    
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:lang,@"c_map_loc_jingdu",lati,@"c_map_loc_weidu",@"10",@"c_map_scalesize",@"10",@"c_map_eventcount",@"1",@"cityid", s_time, @"c_auth_key", [[DataSource shareInstance] md5_hexDigest:[s_time stringByAppendingString:@"gip152i36m8qgl160akn5dpal4"]], @"c_md5_key",nil];
    
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = RECOMMENDMAPEVENT;
    msg.ui_delegate = self;
    [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/api/recommend_map_event.php" postInfo:info userInfo:msg];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    backbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [backbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [backbutton addTarget:self action:@selector(backButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [backButtonItem release];
    
    UIImage* returnImage = [UIImage imageNamed:@"ButtonBag_normal.png"];
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbutton.frame = CGRectMake(0, 0, 51, 30);
    [rightbutton setBackgroundImage:returnImage forState:UIControlStateNormal];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"ButtonBag_pressed.png"] forState:UIControlStateHighlighted];
    [rightbutton addTarget:self action:@selector(returnButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* returnButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = returnButtonItem;
    [returnButtonItem release];
    
    // gets some points
	NSMutableArray * arr = [NSMutableArray array];
	VPPMapAnnotationExample *ann = [[VPPMapAnnotationExample alloc] init];
    if ([_langitude floatValue] > 1000.0) {
        
        _langitude = [NSString stringWithFormat:@"%f",[_langitude floatValue]/100000.0];
    }
    if ([_latitude floatValue] > 1000.0) {
        _latitude = [NSString stringWithFormat:@"%f",[_latitude floatValue]/100000.0];
    }
	ann.coordinate = CLLocationCoordinate2DMake([_langitude floatValue],[_latitude floatValue]);
	ann.pinAnnotationColor = MKPinAnnotationColorPurple;
    ann.title = placeInfo.name;
	ann.opensWhenShown = YES;
    ann.showsDisclosureButton = NO;
	[arr addObject:ann];
	[ann release];
//	ann = [[VPPMapAnnotationExample alloc] init];
//	ann.coordinate = CLLocationCoordinate2DMake(43.3576393127441,-8.4019660949707);
//	ann.title = @"Tabacos";
//    ann.image = [UIImage imageNamed:@"bikePin"];
//	[arr addObject:ann];
//	[ann release];
//	ann = [[VPPMapAnnotationExample alloc] init];
//	ann.coordinate = CLLocationCoordinate2DMake(43.3529319763184,-8.4093017578125);
//	ann.title = @"Estación de Tren";
//	[arr addObject:ann];
//	[ann release];
    
    _mh = [[VPPMapHelper VPPMapHelperForMapView:self.mapView 
                             pinAnnotationColor:MKPinAnnotationColorGreen 
                          centersOnUserLocation:NO
                          showsDisclosureButton:YES 
                                       delegate:self] retain];
    self.mapView.showsUserLocation = YES;
	_mh.userCanDropPin = NO;
	_mh.allowMultipleUserPins = YES;
	_mh.pinDroppedByUserClass = [VPPMapAnnotationExample class];
	[_mh setMapAnnotations:arr];
	
	[_mh release];
    
    NSArray* selectedArray = [[DataSource shareInstance] getCurrentEvent];
    if (selectedArray && [selectedArray count] > 0) {
        selectedCount = [selectedArray count];
        for (PlaceInfo* eventInfo in selectedArray) {
            NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:eventInfo.shopid,@"c_shop_id",nil];
            CoreMsg* msg = [[CoreMsg alloc] init];
            msg.data = SHOPDETAIL;
            msg.ui_delegate = self;
            
            [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_shop_detail" postInfo:info userInfo:msg];
        }
    }
    else
    {
        NSString* templang = [NSString stringWithFormat:@"%f",[_langitude floatValue]*100000];
        NSString* lang = [templang substringToIndex:[templang rangeOfString:@"."].location];
        
        NSString* templati = [NSString stringWithFormat:@"%f",[_latitude floatValue]*100000];
        NSString* lati = [templati substringToIndex:[templati rangeOfString:@"."].location];
        
        NSDate *today = [NSDate date];
        NSTimeInterval time = [today timeIntervalSince1970];
        NSString* temptime = [NSString stringWithFormat:@"%f",time];
        NSString* s_time = [temptime substringToIndex:[temptime rangeOfString:@"."].location];
        
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:lang,@"c_map_loc_jingdu",lati,@"c_map_loc_weidu",@"10",@"c_map_scalesize",@"10",@"c_map_eventcount",[[DataSource shareInstance] getDefaultCityId],@"cityid", s_time, @"c_auth_key", [[DataSource shareInstance] md5_hexDigest:[s_time stringByAppendingString:@"gip152i36m8qgl160akn5dpal4"]], @"c_md5_key",nil];
        
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = RECOMMENDMAPEVENT;
        msg.ui_delegate = self;
        [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/api/recommend_map_event.php" postInfo:info userInfo:msg];
    }
    
//    [arr removeAllObjects];
//    arr = [[NSMutableArray alloc] init ];
//    [arr addObject:[[[UIBarButtonItem alloc] initWithTitle:@"Tons of pins" style:UIBarButtonItemStyleBordered target:self action:@selector(tonsOfPins)] autorelease]];
//    [arr addObject:[[[UIBarButtonItem alloc] initWithTitle:@"Toggle Center on me" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleCenterOnMe)] autorelease]];    
//    self.navigationItem.rightBarButtonItems = arr;
//    [arr release];
//    [self tonsOfPins];
    
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)backButtonPress:(id)sender
{
    BOOL isPop = NO;
//    NSArray* viewControllerArray = [self.navigationController viewControllers];
//    for (UIViewController* viewController in viewControllerArray) {
//        if ([viewController isKindOfClass:[EventEditViewController class]]) {
//            [self.navigationController popToViewController:viewController animated:YES];
//            isPop = YES;
//            break;
//        }
//    }
    if (isPop == NO) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)returnButtonPressed:(id)sender
{
    BOOL isPop = NO;
    NSArray* viewControllerArray = [self.navigationController viewControllers];
    for (UIViewController* viewController in viewControllerArray) {
        if ([viewController isKindOfClass:[EventEditViewController class]]) {
            [self.navigationController popToViewController:viewController animated:YES];
            isPop = YES;
            break;
        }
    }
    for (UIViewController* viewController in viewControllerArray) {
        if ([viewController isKindOfClass:[TravelDetailViewController class]] || [viewController isKindOfClass:[MoreTripDetailViewController class]]) {
            [self.navigationController popToViewController:viewController animated:YES];
            isPop = YES;
            break;
        }
    }
    if (isPop == NO) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark -
#pragma mark VPPMapHelperDelegate

- (void) open:(id<MKAnnotation>)annotation {
//    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Annotation pressed" message:[NSString stringWithFormat:@"It says: %@",annotation.title] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    [av show];
//    [av release];
    NSLog(@"%@",annotation.title);
    PlaceDetailInfo* detailInfo = nil;
    for (PlaceDetailInfo* info in placeArray) {
        if ([info.name isEqual:annotation.title]) {
            detailInfo = info;
            break;
        }
    }
    if (detailInfo == nil) {
        return;
    }
    EventDetailViewController * eventDetailViewController = [[EventDetailViewController alloc] initWithPlaceInfo:detailInfo];
    NSArray* currentArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* place in currentArray) {
        if ([detailInfo.shopid isEqualToString:place.shopid]) {
            eventDetailViewController.isTripExistEvent = YES;
        }
    }
    if (isEdit == NO) {
        eventDetailViewController.isEdit = NO;
        [self.navigationController pushViewController:eventDetailViewController animated:YES];
        [eventDetailViewController release];
    }
    else
    {
        NSArray* viewControllerArray = [self.navigationController viewControllers];
        for (UIViewController* viewController in viewControllerArray) {
            if ([viewController isKindOfClass:[EventEditViewController class]]) {
                [self.navigationController popToViewController:viewController animated:NO];
                eventDetailViewController.delegate = (EventEditViewController*)viewController;
                [viewController.navigationController pushViewController:eventDetailViewController animated:YES];
                [eventDetailViewController release];
                break;
            }
        }
    }
}

- (BOOL) annotationDroppedByUserShouldOpen:(id<MKAnnotation>)annotation {
	VPPMapAnnotationExample *ann = (VPPMapAnnotationExample*)annotation;
	
	ann.title = @"Hi there!";
	ann.pinAnnotationColor = MKPinAnnotationColorGreen;
	
	return YES;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    NSLog(@"haha");
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: RECOMMENDMAPEVENT]) {
        
        placeArray=[[NSMutableArray alloc] initWithArray:data];
        NSMutableArray* tempplaces = [[NSMutableArray alloc] init];
        for (PlaceDetailInfo* detailInfo in data) {
            VPPMapAnnotationExample *place= [[VPPMapAnnotationExample alloc] init];
            NSLog(@"%f",[detailInfo.langitude floatValue]/100000.0);
            place.coordinate = CLLocationCoordinate2DMake([detailInfo.langitude floatValue]/100000.0,[detailInfo.latitude floatValue]/100000.0);
            
            place.pinAnnotationColor = MKPinAnnotationColorPurple;
            place.opensWhenShown = NO;
            place.title = detailInfo.name;
            UIImage *icnImage;
            if ([detailInfo.typeid isEqualToString:@"1"]) {
                icnImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icn_chi.png" ofType:nil]];
            }
            else if ([detailInfo.typeid isEqualToString:@"2"])
            {
                icnImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icn_zhu.png" ofType:nil]];
            }
            else if ([detailInfo.typeid isEqualToString:@"4"])
            {
                icnImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icn_you.png" ofType:nil]];
            }
            else if ([detailInfo.typeid isEqualToString:@"5"])
            {
                icnImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icn_gou.png" ofType:nil]];
            }
            else if ([detailInfo.typeid isEqualToString:@"6"])
            {
                icnImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icn_yu.png" ofType:nil]];
            }
            place.image = icnImage;
//            [icnImage release];
            
            [tempplaces addObject:place];
            [place release];
        }
        _mh.shouldClusterPins = NO;
        [_mh addMapAnnotations:tempplaces];
        [tempplaces release];
    }
    else if ([coreMsg.data isEqual: SHOPDETAIL]) {
        if (selectedPlaceArray == nil) {
            selectedPlaceArray = [[NSMutableArray alloc] init];
        }
        [selectedPlaceArray addObject:data];
        selectedCount --;
        if (selectedCount == 0) {
            NSMutableArray* tempplaces = [[NSMutableArray alloc] init];
            CGFloat distance = 0.0;
            CLLocation * Location = [[CLLocation alloc]initWithLatitude:[_langitude floatValue] longitude:[_latitude floatValue]];
            for (PlaceDetailInfo* detailInfo in selectedPlaceArray) {
                if (![detailInfo.latitude isKindOfClass:[NSString class]] || [detailInfo.latitude floatValue] == 0.0 || ![detailInfo.langitude isKindOfClass:[NSString class]] || [detailInfo.langitude floatValue] == 0.0)
                {
                    continue;
                }
                VPPMapAnnotationExample *place= [[VPPMapAnnotationExample alloc] init];
                place.coordinate = CLLocationCoordinate2DMake([detailInfo.langitude floatValue],[detailInfo.latitude floatValue]);
                
                place.pinAnnotationColor = MKPinAnnotationColorPurple;
                place.opensWhenShown = NO;
                place.showsDisclosureButton = NO;
                place.title = detailInfo.name;
                
                [tempplaces addObject:place];
                [place release];
                
                CLLocation * newLocation = [[CLLocation alloc]initWithLatitude:[detailInfo.langitude floatValue] longitude:[detailInfo.latitude floatValue]];
                
                CGFloat tempDistance = [Location distanceFromLocation:newLocation];
                if (tempDistance > distance) {
                    distance = tempDistance*1.5;
                }
                if (distance < 1500) {
                    distance = 1500;
                }
                [newLocation release];
            }
            
            
            //关键就在这里，取得两个cllocation间的距离，单位是m
//            CLLocationDistance newDistance = [[locmanager location] distanceFromLocation:newLocation];
            //下面是设置mapView的显示区域，使得这两个地点都能出现在地图中，这里就用到了刚算出来的距离。
            
            _mh.shouldClusterPins = NO;
            [_mh addMapAnnotations:tempplaces];
            [tempplaces release];
            
            MKCoordinateRegion region;
            region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake([_langitude floatValue],[_latitude floatValue]), distance, distance);
            region = [_mh.mapView regionThatFits:region];
            
            [_mh.mapView setRegion:region animated:YES];
            
            [Location release];
            
            if (isEdit == NO) {
                return;
            }
            NSString* templang = [NSString stringWithFormat:@"%f",[_langitude floatValue]*100000];
            NSString* lang = [templang substringToIndex:[templang rangeOfString:@"."].location];
            
            NSString* templati = [NSString stringWithFormat:@"%f",[_latitude floatValue]*100000];
            NSString* lati = [templati substringToIndex:[templati rangeOfString:@"."].location];
            
            NSDate *today = [NSDate date];
            NSTimeInterval time = [today timeIntervalSince1970];
            NSString* temptime = [NSString stringWithFormat:@"%f",time];
            NSString* s_time = [temptime substringToIndex:[temptime rangeOfString:@"."].location];
            
            NSNumber* number = [NSNumber numberWithDouble:distance];
            NSString* s_distance = [NSString stringWithFormat:@"%d",[number intValue]/100];
            
            NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:lang,@"c_map_loc_jingdu",lati,@"c_map_loc_weidu",s_distance,@"c_map_scalesize",@"10",@"c_map_eventcount",[[DataSource shareInstance] getDefaultCityId],@"cityid", s_time, @"c_auth_key", [[DataSource shareInstance] md5_hexDigest:[s_time stringByAppendingString:@"gip152i36m8qgl160akn5dpal4"]], @"c_md5_key",nil];
            
            CoreMsg* msg = [[CoreMsg alloc] init];
            msg.data = RECOMMENDMAPEVENT;
            msg.ui_delegate = self;
            [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/api/recommend_map_event.php" postInfo:info userInfo:msg];
        }
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: TRAVELEDITLINE]) {
    }
}


@end
